package controller;

import com.alibaba.fastjson.JSONObject;
import dao.DaoException;
import dao.customerDao.CustomerDaoImpl;
import model.Customer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/ShowServlet")
public class ShowServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CustomerDaoImpl dao = new CustomerDaoImpl();

        ArrayList<Customer> customers;
        try {
            int pageNum = Integer.parseInt(request.getParameter("page"));
            int pageSize = Integer.parseInt(request.getParameter("limit"));
            int count = dao.findCustomerNum();
            customers = dao.findCustomerByPage(pageNum, pageSize);

            Map<String, Object> map = new HashMap<>();
            map.put("code", 0);
            map.put("msg", "");
            map.put("count", count);
            map.put("data", customers);

            JSONObject json = new JSONObject(map);
            // 解决跨域问题(如果在同一个项目下不需要解决)
//            response.setHeader("Access-Control-Allow-Origin", "*");

            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(json.toJSONString());
        } catch (DaoException e) {
            e.printStackTrace();
        }
    }
}
